package com.z.sys.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
 
public class EmailUtil {
 
    public static void sendEmail(String recipient, String subject, String content) throws MessagingException {
        final String username = "zxyjavaweb@163.com"; // 163邮箱用户名
        final String password = "BHVRBAEBOZPSWWUZ";//"RAHLAFYRGNRVAWTX"; // 授权码
 
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.163.com"); // SMTP服务器地址
        props.put("mail.smtp.auth", "true"); // 是否需要认证
        props.put("mail.smtp.port", "465"); // SMTP服务器端口
        props.put("mail.smtp.ssl.enable", "true"); // 启用SSL
 
        // 创建认证器
        Authenticator auth = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };
 
        // 创建会话
        Session session = Session.getInstance(props, auth);
 
        // 创建邮件
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
        message.setSubject(subject);
        message.setText(content);
 
        // 发送邮件
        Transport.send(message);
    }
 
    public static void main(String[] args) {
        try {
            sendEmail("184100072@qq.com", "Test Subject", "This is the email content");
            System.out.println("Email sent successfully");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("Error sending email");
        }
    }
}